/**
 * 내용 1. 송수신 내용 표시
 * 		2. 클라이언트 관리
 * 		3. 송신할 클라이언트 선택
 */

package jong;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.text.*;
import java.util.*;

import javax.swing.*;
import javax.swing.border.*;

public class MultiChatServer extends JFrame implements Runnable {
	SocketData socketData = null;
	ServerSocket server = null;
	Socket socket = null;
	InetAddress ia = null;
	MultiChatServerThread mcst = null;
	
	int port = 4444;
	boolean tFlag = false;
	StringBuilder data = new StringBuilder();
	HashMap<String, MultiChatServerThread> clients = new HashMap<String, MultiChatServerThread>();
	SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
	
	DefaultListModel model = new DefaultListModel();

	private JPanel contentPane;
	private JPanel panel;
	private JButton btnStop;
	private JButton btnStart;
	private JPanel panel_1;
	private JButton btnNewButton_2;
	private JTextField message;
	private JComboBox comboBox;
	private JPanel panel_2;
	private JLabel lblNewLabel;
	private JScrollPane scrollPane;
	private JList list;
	private JPanel panel_3;
	private JSeparator separator;
	private JScrollPane scrollPane_1;
	private JTextPane result;
	private JSeparator separator_1;
	private JSeparator separator_2;
	private JLabel label;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					MultiChatServer frame = new MultiChatServer();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public MultiChatServer() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 600, 355);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);
		contentPane.add(getPanel(), BorderLayout.NORTH);
		contentPane.add(getPanel_1(), BorderLayout.SOUTH);
		contentPane.add(getPanel_2_1(), BorderLayout.WEST);
		contentPane.add(getPanel_3(), BorderLayout.CENTER);
		try{
			ia = InetAddress.getLocalHost();
			setTitle("서버 IP : [" + ia.getHostAddress() + "]   포트 : [" + port + "]");
		}catch(Exception ex){
			ex.getMessage();
		}
		btnStop.setEnabled(false);
	}

	@Override
	public void run() {
		try {
			server = new ServerSocket(port);
			tFlag = true;

			while(tFlag){
				socket = server.accept();
				mcst = new MultiChatServerThread(this, socket);
				mcst.start();
			}
		} catch (Exception ex) {
			ex.getStackTrace();
		} finally {
			
		}
	}

	public void serverStart() {
		try {
			dataSet("<hr/><font color='red'>서버가 시작되었습니다.</font><br/>" +
					"<font color='blue'>서버 시작 시간 : " + sd.format(new Date()) + "</font><br/><hr/>");
			
			btnStart.setEnabled(false);
			btnStop.setEnabled(true);
			
			Thread t = new Thread(this);
			t.start();
			
		} catch (Exception ex) {
			ex.getStackTrace();
		}
	}

	public void serverStop() {
		try {

		} catch (Exception ex) {
			ex.getStackTrace();
		}
	}

	public void sendMsg(String s) {
		try {
			SocketData sd = new SocketData("login", mcst.sd.getUser(), mcst.sd.getMessage(), null);
			sd.setMessage(s);
			mcst.send.writeObject(sd);
			dataSet(sd);
			message.setText("");
		} catch (Exception ex) {
			ex.getStackTrace();
		}
	}
	public void dataSet(SocketData sd){
		data.append("[" + sd.getUser() + "]" + sd.getMessage() + "<br/>");
		result.setText(data.toString());
	}
	
	public void dataSet(String str){
		data.append(str + "<br/>");
		result.setText(data.toString());
	}
	
	private JButton getBtnStart() {
		if (btnStart == null) {
			btnStart = new JButton("서버시작");
			btnStart.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					serverStart();
				}
			});
			btnStart.setPreferredSize(new Dimension(81, 30));
		}
		return btnStart;
	}

	private JButton getBtnStop() {
		if (btnStop == null) {
			btnStop = new JButton("서버종료");
			btnStop.setPreferredSize(new Dimension(100, 23));
			btnStop.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					serverStop();
				}
			});
		}
		return btnStop;
	}

	private JButton getBtnNewButton_2() {
		if (btnNewButton_2 == null) {
			btnNewButton_2 = new JButton("전송");
			btnNewButton_2.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					sendMsg(message.getText());
				}
			});
			btnNewButton_2.setPreferredSize(new Dimension(100, 30));
		}
		return btnNewButton_2;
	}

	private JTextField getMessage() {
		if (message == null) {
			message = new JTextField();
			message.addKeyListener(new KeyAdapter() {
				@Override
				public void keyReleased(KeyEvent e) {
					if (e.getKeyCode() == KeyEvent.VK_ENTER) {
						sendMsg(message.getText());
					}
				}
			});
			message.setColumns(10);
		}
		return message;
	}

	private JPanel getPanel() {
		if (panel == null) {
			panel = new JPanel();
			panel.setLayout(new BorderLayout(0, 0));
			panel.add(getBtnStop(), BorderLayout.EAST);
			panel.add(getBtnStart(), BorderLayout.CENTER);
			panel.add(getSeparator_2(), BorderLayout.SOUTH);
		}
		return panel;
	}

	private JPanel getPanel_1() {
		if (panel_1 == null) {
			panel_1 = new JPanel();
			panel_1.setLayout(new BorderLayout(0, 0));
			panel_1.add(getBtnNewButton_2(), BorderLayout.EAST);
			panel_1.add(getMessage(), BorderLayout.CENTER);
			panel_1.add(getComboBox(), BorderLayout.WEST);
			panel_1.add(getSeparator_1(), BorderLayout.NORTH);
		}
		return panel_1;
	}

	private JComboBox getComboBox() {
		if (comboBox == null) {
			comboBox = new JComboBox();
			comboBox.setPreferredSize(new Dimension(70, 21));
			comboBox.setName("이모티콘");
		}
		return comboBox;
	}

	private JPanel getPanel_2_1() {
		if (panel_2 == null) {
			panel_2 = new JPanel();
			panel_2.setLayout(new BorderLayout(0, 0));
			panel_2.add(getScrollPane(), BorderLayout.WEST);
		}
		return panel_2;
	}

	private JLabel getLblNewLabel() {
		if (lblNewLabel == null) {
			lblNewLabel = new JLabel("접속자 목록");
			lblNewLabel.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null,
					null));
			lblNewLabel.setOpaque(true);
			lblNewLabel.setBackground(Color.LIGHT_GRAY);
			lblNewLabel.setPreferredSize(new Dimension(64, 20));
			lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
		}
		return lblNewLabel;
	}

	private JScrollPane getScrollPane() {
		if (scrollPane == null) {
			scrollPane = new JScrollPane();
			scrollPane.setPreferredSize(new Dimension(170, 200));
			scrollPane.setViewportView(getList());
			scrollPane.setColumnHeaderView(getLblNewLabel());
		}
		return scrollPane;
	}

	private JList getList() {
		if (list == null) {
			list = new JList();
			list.setPreferredSize(new Dimension(160, 0));
		}
		return list;
	}

	private JPanel getPanel_3() {
		if (panel_3 == null) {
			panel_3 = new JPanel();
			panel_3.setLayout(new BorderLayout(0, 0));
			panel_3.add(getSeparator(), BorderLayout.WEST);
			panel_3.add(getScrollPane_1(), BorderLayout.CENTER);
		}
		return panel_3;
	}

	private JSeparator getSeparator() {
		if (separator == null) {
			separator = new JSeparator();
			separator.setEnabled(false);
			separator.setForeground(Color.LIGHT_GRAY);
			separator.setPreferredSize(new Dimension(10, 2));
		}
		return separator;
	}

	private JScrollPane getScrollPane_1() {
		if (scrollPane_1 == null) {
			scrollPane_1 = new JScrollPane();
			scrollPane_1.setViewportView(getResult());
			scrollPane_1.setColumnHeaderView(getLabel());
		}
		return scrollPane_1;
	}

	private JTextPane getResult() {
		if (result == null) {
			result = new JTextPane();
			result.setContentType("text/html");
		}
		return result;
	}

	private JSeparator getSeparator_1() {
		if (separator_1 == null) {
			separator_1 = new JSeparator();
			separator_1.setForeground(Color.WHITE);
			separator_1.setPreferredSize(new Dimension(0, 10));
		}
		return separator_1;
	}

	private JSeparator getSeparator_2() {
		if (separator_2 == null) {
			separator_2 = new JSeparator();
			separator_2.setEnabled(false);
			separator_2.setForeground(UIManager.getColor("Panel.background"));
			separator_2.setPreferredSize(new Dimension(0, 10));
		}
		return separator_2;
	}

	private JLabel getLabel() {
		if (label == null) {
			label = new JLabel("내용");
			label.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
			label.setPreferredSize(new Dimension(64, 20));
			label.setOpaque(true);
			label.setHorizontalAlignment(SwingConstants.CENTER);
			label.setBackground(Color.LIGHT_GRAY);
		}
		return label;
	}
}
